<template>
	<view>
		<view class="search-head">
			<!-- <input class="inpt" v-if="contacts.length>0 || isSearch" type="text" placeholder="搜索联系人" @input="onSearchInput" /> -->
			<uni-search-bar @confirm="confirm" :radius="50" placeholder="搜索联系人"></uni-search-bar>
		</view>
		<view class="text-head">
			好友列表
		</view>
		<view v-if="contacts.length>0">
			<scroll-view class="contact-scroll" scroll-y :scroll-into-view="scrollViewId">
				<checkbox-group class="uni-list" @change="radioChange">
				<view class="box" v-for="(item,key) in contacts" :key="key">
					<view class="divider" :id="item.letter">
						<text class="divider-text">{{item.letter}}</text>
					</view>
					<view class="item" hover-class="hover" hover-start-time="20" v-for="(contact,index) in item.contacts" :key="index"
					 @click='onSelectClick(contact)'>
							<view class="uni-list-cell uni-list-cell-pd">
								<checkbox :value="JSON.stringify(contact)">
									<image class="portrait" :src="(contact.avatar &&(contact.avatar .indexOf('http')!=-1))?contact.avatar :defheadimg" mode="aspectFill"></image>
									<view class="name">{{contact.name}}</view>
								</checkbox>
							</view>
						
					</view>
				</view>
				</checkbox-group>
			</scroll-view>
			<view class="indexBar-bg">
				<view class="indexBar" catchtouchmove>
					<view class="indexBar-box" @touchstart="tStart" @touchend="tEnd" @touchmove="tMove">
						<view  class="indexBar-item" :style="{backgroundColor:letter==item.letter?'#00ACFE':'' ,color:letter==item.letter?'#ffffff':''}" v-for="(item,index) in contacts" :key="index" :id="item.letter" @touchstart="getCur"
						 @touchend="setCur">
							{{item.letter}}
						</view>
					</view>
				</view>
			</view>
			<view v-show="!hidden" class="indexToast">{{letter}}</view>
		</view>
		<text v-else class="no-contact">通讯录暂无联系人</text>
		<!-- 分享示例 -->
		<uni-popup id="popupShare" ref="popupShare" type="share">
			<view class="uni-flex uni-row share" style="background-color: #fff;height: 110rpx;align-items: center;border-radius: 32rpx 32rpx 0 0;">
				<view style="-webkit-flex: 1;flex: 1;margin-left: 20rpx;">

				</view>
				<view style="-webkit-flex: 1;flex: 1;text-align: center;font-size: 28rpx;color: #333333;font-weight: bold;">

				</view>
				<view class="text" style="-webkit-flex: 1;flex: 1;margin-right: 30rpx;">
					<i class="iconfont iconcuo" style="color: #DCDFE6;font-size: 40rpx;background-color: #F4F7FC;border-radius: 100rpx;"
					 @click="closeShare"></i>
				</view>
			</view>
			<view class="uni-flex uni-column" style="background-color: #FFFFFF;">
				<view class="text" style="-webkit-flex: 1;flex: 1;">
					<view class="uni-flex uni-row" style="justify-content: space-around;">
						<view class="text" style="margin: 10rpx;height: 158rpx;width: 500rpx;margin: 0 30rpx 0 30rpx;">
							<view class="uni-input-wrapper">
								<input v-model="messages" style="border-radius: 25rpx;background-color: #FAFAFA;" class="uni-input" maxlength="10" placeholder="有什么想和好友说的..." />
							</view>
						</view>
						<view class="text" style="margin-right: 30rpx;">
							<image mode="aspectFill" :src="senddata.img_url" style="width: 160rpx;height: 160rpx;"></image>
						</view>
					</view>
				</view>
				<view class="text" style="-webkit-flex: 1;flex: 1;margin-top: 52rpx;">
					<button @click="sendMsg" style="background-color: #00D5A2;color: #FFFFFF;height: 80rpx;font-size: 28rpx;line-height: 80rpx;font-weight: bold;">发送</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import utils from '@/common/util.js'
	import PinyinUtils from '@/pages/album/components/pinyin/pinyin2.js'
	var platform = uni.getSystemInfoSync().platform
	export default {
		data() {
			return {
				defheadimg:'',
				nicheng:'',
				/* 侧边栏选择器 */
				scrollViewId: "wo",
				letter: '',
				boxTop: 0,
				barHeight: 0,
				minHeight: 0,
				hidden: true,
				/* 联系人 */
				contacts: [],
				name: [{
						name: '这这'
					},
					{
						name: '啊啊'
					},
					{
						name: '嘿嘿'
					},
					{
						name: '芜湖'
					},
					{
						name: '啦啦'
					},
					{
						name: '嘻嘻'
					},
					{
						name: '哈哈'
					},
					{
						name: '嘎嘎'
					},
					{
						name: '呵呵'
					},
					{
						name: '#￥%'
					},
					{
						name: '#￥%'
					},
					{
						name: '1￥%'
					},
				],
				contactItems: [],
				isSearch: false,
				isShow: false,
				img: null, //私信时显示的图片
				messages:'',
				socketTask:'',
				fromUserinfo:uni.getStorageSync('userInfo'),
				token:uni.getStorageSync('token'),
				toid:[],
				users:[],
				senddata:[]
			}
		},
		onLoad(e) {
			this.defheadimg= this.defimg;
			this.senddata = JSON.parse(e.data);
			
			
			const res = uni.getSystemInfoSync();
			this.barHeight = res.windowHeight / 27;
			//初始通讯录
			this.initContacts()
			this.createStock();
		},
		onReady() {
			var that = this
			uni.createSelectorQuery().select('.indexBar-box').boundingClientRect(function(e) {
				if (e != null) {
					that.boxTop = e.top
				}
			}).exec()
		},
		onNavigationBarButtonTap(item) {
			if (item.index == 0) {
				this.$refs.popupShare.open()
			}
		},
		methods: {
			confirm:function(e){
				this.nicheng = e.value;
				this.contacts=[];
				this.initContacts();
			},
			/* 创建连接 */
			createStock() {
				this.socketTask = uni.connectSocket({
					url: 'ws://'+this.chatsevenUrl+'?token='+this.token,
					success: (res) => {}
				})
				this.socketTask.onOpen(() => {
					this.socketTask.send({
						data: "测试推送",
						async success() {
							console.log("消息发送成功");
						},
					});
					this.listenMessage()
				})
			},
			// 发送消息
			sendMsg() {
				var obj = {
					k_token:this.token,
					toid:this.toid,
					fromid:this.fromUserinfo['id'],
				}
				if(this.messages){
					obj.content = this.messages;
					obj.content_type = 1;
					this.socketTask.send({
						data: JSON.stringify(obj),
						success: (res) => {
							
						}
					});
				}
				if(this.senddata.type=="video"){
					obj.content = this.senddata.vido_url;
					obj.content_type = 4;
				}
				if(this.senddata.type=="image"){
					obj.content = this.senddata.img_url;
					obj.content_type = 2;
				}
				this.socketTask.send({
					data: JSON.stringify(obj),
					success: (res) => {
						console.log("发送成功");
						uni.showToast({
							title: '转发成功!'
						});
					}
				});
				let time = new Date().getTime()/1000;
				this.users.forEach((item,key)=>{
					let content = ""
					if(this.senddata.type=="video"){
						content = '[视频]';
					}else{
						content = '[图片]';
					}
					utils.Saveuser(item,content,parseInt(time));
				})
				setTimeout(function(){
					uni.redirectTo({
						url:'message'
					})
				},1000);
			},
			
			radioChange: function(e) {
				let selindex= e.detail.value;
				this.toid = [];
				this.users =[];
				console.log(selindex,"===");
				selindex.forEach((item,key)=>{
					let data = JSON.parse(item);
					this.toid.push(data.userId);
					let obj={
						user_id:data.userId,
						nicheng:data.name,
						avatar:data.avatar,
						is_mutual_follow:data.c_type==1?1:null
					}
					this.users.push(obj);
				})
			},
			/*
			 * 滑动的侧边选择器
			 */
			getCur(e) {
				this.hidden = false
				this.letter = e.target.id
			},
			setCur(e) {
				this.hidden = true;
				this.letter = e.target.id
			},
			tMove(e) {
				console.log("===111=");
				var y = e.touches[0].clientY
				var offsettop = this.boxTop
				//判断选择区域,只有在选择区才会生效
				if (y > offsettop) {
					var num = Math.floor((y - offsettop) / this.barHeight);
					if (num < this.contacts.length) {
						this.letter = this.contacts[num].letter
						this.scrollViewId = this.letter
					}
				}
			},
			tStart() {
				this.hidden = false
			},
			tEnd() {
				this.hidden = true;
			},
			// guanzhu() {
			// 	let resData = {
			// 		form_id: 1107
			// 	}
			// 	this.$api.apiPost('user/video.User/UserFollowAdd', resData).then(res => {
			// 		console.log('res', res)
			// 	})
			// },
			/* 
			 * 初始化通讯录
			 */
			initContacts: function() {
				let abc = null
				let abcArr = []
				let arr = []
				const userInfo = uni.getStorageSync('userInfo')
				let resData = {
					form_id: userInfo.id
				}
				if(this.nicheng){
					resData['nicheng'] = this.nicheng;
				}
				this.$api.apiPost('user/video.User/UserFriendsList', resData).then(res => {
					const data = res.data
					console.log(data)
					if (data.code == 200) {
						// 获取首字母
						for (var i = 0; i < data.data.data.length; i++) {
							if(!data.data.data[i].nicheng){
								data.data.data[i].nicheng = '未设置昵称'
							}
							abc = PinyinUtils.chineseToPinYin(data.data.data[i].nicheng).slice(0, 1)
							//isNaN(abc)判断abc是不是汉字
							if (isNaN(abc) == true) {
								abcArr.push(abc)
								//isNaN(abc)判断abc是不是数字或符号
							} else if (isNaN(abc) == false) {
								abcArr.push('#')
							}
							// console.log('abc', abc, isNaN(abc))
						}
						// console.log('abcArr', abcArr)
						// 首字母去重
						for (var i = 0; i < abcArr.length; i++) {
							if (arr.indexOf(abcArr[i]) == -1) {
								arr.push(abcArr[i]);
							}
						}
						// console.log('首字母去重', arr)
						/* for (var i = 0; i < arr.length; i++) {
							this.contacts.push({letter:arr[i],contacts:[]})
							for (var j = 0; j < this.name.length; j++) {
								if(arr[i] == PinyinUtils.chineseToPinYin(this.name[j].name).slice(0,1)){
									this.contacts[i].contacts.push({name:this.name[j].name})
								}
								if(arr[i] == '#'&&isNaN(PinyinUtils.chineseToPinYin(this.name[j].name))==false){
									this.contacts[i].contacts.push({name:this.name[j].name})
								}
							}
						} */
						for (var i = 0; i < arr.length; i++) {
							this.contacts.push({
								letter: arr[i],
								contacts: []
							})
							for (var j = 0; j < data.data.data.length; j++) {
								if (arr[i] == PinyinUtils.chineseToPinYin(data.data.data[j].nicheng).slice(0, 1)) {
									this.contacts[i].contacts.push({
										name: data.data.data[j].nicheng,
										userId: String(data.data.data[j].user_id),
										avatar: data.data.data[j].avatar
									})
								}
								if (arr[i] == '#' && isNaN(PinyinUtils.chineseToPinYin(data.data.data[j].nicheng)) == false) {
									this.contacts[i].contacts.push({
										name: data.data.data[j].nicheng,
										userId: String(data.data.data[j].user_id),
										avatar: data.data.data[j].avatar
									})
								}
							}
						}
						// console.log('contacts', this.contacts)
						// 首字母排序
						this.contacts.sort(function(a, b) {
							return (a.letter + '').localeCompare(b.letter + '')
						})
						// console.log('排序contacts', this.contacts)
						for (var i = 0; i < this.contacts.length; i++) {
							console.log(this.contacts[i].letter)
						}
					}
				})
			},
			/* 
			 * 点击联系人
			 */
			onSelectClick: function(contact) {
				/* uni.showActionSheet({
					itemList: ['电话联系'],
					success: (e) => {
						if (e.tapIndex == 0) {
							uni.makePhoneCall({
								phoneNumber: contact.phone
							});
						}
					}
				}) */
			},
			/* 
			 * 搜索
			 */
			onSearchInput: function(e) {
				var searchVal = e.detail.value
				this.isSearch = true
				if (searchVal == '') {
					this.contacts = JSON.parse(JSON.stringify(this.contactItems))
					this.isSearch = false
				} else {
					var showList = []
					var list = []
					list = JSON.parse(JSON.stringify(this.contactItems))
					list.forEach((item, index1) => {
						var contacts = []
						item.contacts.forEach((contact, index2) => {
							for (var i = 0; i < searchVal.length; i++) {
								if (contact.name.indexOf(searchVal[i]) != -1) {
									var contain = false;
									contacts.find(function(val) {
										if (val.phone == contact.phone) {
											contain = true;
										}
									});
									if (!contain) {
										contacts.push(contact);
									}
								}
							}
						})
						if (contacts.length > 0) {
							var contacts = {
								letter: item.letter,
								contacts: contacts
							}
							showList = showList.concat(contacts)
						}
					})
					setTimeout(() => {
						this.contacts = JSON.parse(JSON.stringify(showList))
					}, 200)
				}
			},
			/* 关闭分享弹窗 */
			closeShare() {
				console.log('关闭分享')
				this.$refs.popupShare.close()
			},
		}
	}
</script>

<style scoped>
	/deep/ .uni-input {
		padding: 0rpx;
	}

	/deep/ .uni-input-placeholder {
		padding-left: 30rpx;
		color: #C0C4CC;
		font-weight: bold;
		color: 24rpx;
	}

	/deep/ .uni-list-cell-pd {
		padding: 20rpx 0rpx 22rpx 28rpx;
	}

	/deep/ uni-checkbox:not([disabled]) .uni-checkbox-input:hover {}

	/deep/ uni-checkbox .uni-checkbox-input {
		border-radius: 100rpx;
		background-color: #FFFFFF;
		color: #FFFFFF;
		width: 40rpx;
		height: 40rpx;
	}

	/deep/ uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked {
		border-color: #00D5A2;
		background-color: #00D5A2;
	}

	/deep/ uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked:before {
		color: #FFFFFF;
	}

	.content {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
		width: 100%;
		height: 100%;
	}

	.inpt {
		background-color: #FAFAFA;
		width: 550rpx;
		height: 60rpx;
		font-size: 24rpx;
		font-weight: bold;
		border-radius: 30rpx;
	}

	.search-head {
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: space-around;
		
	}

	.text-head {
		color: #333333;
		font-size: 26upx;
		padding: 30upx 30upx;
		width: calc(100% - 60upx);
		border-top: 1upx solid #EEEEEE;
		margin-top: 20upx;
	}

	.contact-scroll {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
		width: 100vw;
		height: calc(100vh - 90rpx);
	}

	.box {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
		width: 100%;
	}

	.divider {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #FAFAFA;
	}

	.divider-text {
		margin-left: 20rpx;
		font-size: 34upx;
		font-weight: 400;
		color: #999999;
	}

	.item {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: center;
		width: 100%;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.portrait {
		width: 80rpx;
		height: 80rpx;
		border-radius: 100rpx;
		margin: 0 24rpx 0 20rpx;
	}

	.name {
		font-size: 32rpx;
		text-align: left;
		font-weight: 400;
		color: #333333;
	}

	.hover {
		background-color: #e7e7e7;
	}

	.indexBar-bg {
		position: absolute;
		top: 320rpx;
		right: 70rpx;
		/* height: 65vh;
		margin-top: 45px;
		margin-bottom: 1000px;
		width: 60px;
		position: fixed;
		right: 0;
		top: 0;
		z-index: 1000; */
	}

	.indexBar {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(0, -50%);
		display: flex;
		align-items: center;
	}

	.indexBar .indexBar-box {
		width: 60rpx;
		height: auto;
		background: #fff;
		display: flex;
		flex-direction: column;
		border-radius: 10rpx;
	}

	.indexBar-item {
		flex: 1;
		width: 30rpx;
		height: 30rpx;
		border-radius: 50%;
		line-height: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #888;
		margin-bottom: 8upx;
	}

	.indexToast {
		position: fixed;
		top: 0;
		right: 80rpx;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		width: 100rpx;
		height: 100rpx;
		border-radius: 10rpx;
		margin: auto;
		color: #fff;
		line-height: 100rpx;
		text-align: center;
		font-size: 48rpx;
	}

	.no-contact {
		position: fixed;
		width: 100%;
		margin-top: 300rpx;
		font-size: 35rpx;
		color: #666666;
		text-align: center;
	}

	.flex-item {
		width: 100%;
		//height: 100rpx;
		text-align: center;
		line-height: 100rpx;
	}

	.flex-item-V {
		border: 1upx solid #DADADA;
		width: 100%;
		//height: 150rpx;
		text-align: center;
		line-height: 150rpx;
		border: 0rpx;
	}

	.share {
		height: 40rpx;
		background-color: #F2F9FF;
		border-top-right-radius: 50rpx;
		border-top-left-radius: 50rpx;
		text-align: right;
	}

</style>
